package io.lckgroup.modules.lck.controller.wxmp;

import io.lckgroup.common.utils.Constant;
import io.lckgroup.common.utils.R;
import io.lckgroup.modules.lck.entity.CustomerInfoEntity;
import io.lckgroup.modules.lck.service.CustomerInfoService;
import io.lckgroup.modules.lck.utils.GetWxUserOpenidUtil;
import io.lckgroup.modules.lck.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * @author huangrui
 * usercontroller 用户
 */
@RestController
@RequestMapping("/mp/user")

public class UserController {
    //  小程序信息
    private String appid = Constant.WeixinMPConfig.APPID;
    private String APPSecret = Constant.WeixinMPConfig.APPSECRET;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private CustomerInfoService customerInfoService;

    /**
     * 功能描述: <br>
     * 〈〉微信登录
     *
     * @Param: []
     * @Return: java.lang.String
     * @author huangrui
     * @Date: 2020/1/22 14:45
     */
    @PostMapping("/weixinlogin")
    public R weixinlogin(@RequestBody Map<String, String> info) {
        Map map = new HashMap();
        String openid = GetWxUserOpenidUtil.getWxUserOpenid(info.get("code"), appid, APPSecret);
        System.out.println(openid);

        if (openid != null && openid != "") {
//            登录成功,使用opendi查询当前用户
            CustomerInfoEntity userinfoDetails = new CustomerInfoEntity();
            userinfoDetails.setHeadImg(info.get("headImg"));
            Integer i = new Integer(info.get("sex"));
            userinfoDetails.setSex(i);
            userinfoDetails.setNickname(info.get("nickname"));
            userinfoDetails.setOpenId(openid);
//            判断是否为第一次登录,返回null是第一次登录，保存当前用户，不是null说明用户已经存在
            CustomerInfoEntity custom = customerInfoService.getCustomerByOpenid(userinfoDetails.getOpenId());
            if (custom == null) {
                custom = customerInfoService.saveAndSelectCustomer(userinfoDetails);
            }
            custom.setOpenId("");
            //生成token
            String token = jwtUtils.generateToken(custom.getId());
            map.put("token", token);
            map.put("expire", jwtUtils.getExpire());
            System.out.println("tocken:"+token);
            return R.ok().put("data", map);
        } else {
//            登录失败
            return R.error("登录失败");
        }
    }

}
